package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.entity.AttendanceRecord;
import org.example.entity.BusinessTrip;
import org.example.models.R;
import org.example.service.AttendanceRecordService;
import org.example.service.BusinessTripService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.List;

/**
 * @Author: 鸢一折纸
 * @Email: 3498881048@qq.com
 * @Date: 2025/09/15 11:25
 * @Description:
 **/

@RestController
@RequestMapping("/businessTrip")
public class BusinessTripController {

    @Autowired
    private BusinessTripService businessTripService;
    @Autowired
    private AttendanceRecordService attendanceRecordService;

    @GetMapping("/page")
    public R<Page<BusinessTrip>> getAllBusinessTrip(
            @RequestParam(name = "current", defaultValue = "1") int current,
            @RequestParam(name = "size", defaultValue = "4") int size,
            @RequestParam(name = "userId", required = false) Integer userId,
            @RequestParam(name = "applicationDate", required = false) String applicationDate
    ) {
        QueryWrapper<BusinessTrip> query = new QueryWrapper<>();
        query.lambda().eq(BusinessTrip::getUserId, userId);

        if (applicationDate != null && !applicationDate.isEmpty()) {
            query.lambda().like(BusinessTrip::getApplicationDate, applicationDate);
        }

        query.lambda().orderByDesc(BusinessTrip::getApplicationDate);

        Page<BusinessTrip> page = new Page<>(current, size);
        businessTripService.page(page, query);
        return R.success(page);
    }

    @PostMapping("/insert")
    public R<String> insert(@RequestBody BusinessTrip businessTrip, @RequestAttribute("userId") Integer userId) {
        businessTrip.setUserId(userId);

        // 查询指定日期范围内的考勤记录
        QueryWrapper<AttendanceRecord> attendanceQuery = new QueryWrapper<>();
        attendanceQuery.lambda()
                .eq(AttendanceRecord::getUserId, userId)
                .between(AttendanceRecord::getRecordDate, businessTrip.getStartDate(), businessTrip.getEndDate());

        attendanceQuery.and(wrapper ->
                wrapper.ne("morning_status", "未签到")
                        .ne("morning_status", "正常")
                        .or()
                        .ne("afternoon_status", "未签到")
                        .ne("afternoon_status", "正常")
        );

        List<AttendanceRecord> list = attendanceRecordService.list(attendanceQuery);

        long count = attendanceRecordService.count(attendanceQuery);

        // 如果存在不符合条件的记录，则返回错误信息
        if (count > 0) {
            return R.error("日期范围内有日期被占用");
        }

        // 获取今天的日期
        LocalDate today = LocalDate.now();
        LocalDate startDate = businessTrip.getStartDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        // 判断开始日期是否为今天
        if (startDate.equals(today)) {
            // 获取当前时间
            LocalTime now = LocalTime.now();

            // 如果当前时间为下午（12点之后）
            if (now.isAfter(LocalTime.NOON)) {
                return R.error("当前时间为下午，请从明天开始申请出差");
            }
            // 如果是上午，则跳过上午，只更新下午到结束日期
            else {
                boolean save = businessTripService.save(businessTrip);

                if (save) {
                    // 只更新下午状态，跳过上午
                    boolean update = attendanceRecordService.update(
                            Wrappers.<AttendanceRecord>lambdaUpdate()
                                    .set(AttendanceRecord::getAfternoonStatus, "出差")
                                    .eq(AttendanceRecord::getUserId, userId)
                                    .between(AttendanceRecord::getRecordDate, businessTrip.getStartDate(), businessTrip.getEndDate()));

                    if (update) {
                        return R.success("出差申请提交成功");
                    } else {
                        return R.error("出差申请提交失败");
                    }
                } else {
                    return R.error("出差申请提交失败");
                }
            }
        }

        boolean save = businessTripService.save(businessTrip);

        if (save) {
            boolean update = attendanceRecordService.update(
                    Wrappers.<AttendanceRecord>lambdaUpdate()
                            .set(AttendanceRecord::getMorningStatus, "出差")
                            .set(AttendanceRecord::getAfternoonStatus, "出差")
                            .eq(AttendanceRecord::getUserId, userId)
                            .between(AttendanceRecord::getRecordDate, businessTrip.getStartDate(), businessTrip.getEndDate()));
            if (update) {
                return R.success("出差申请提交成功");
            } else {
                return R.error("出差申请提交失败");
            }
        } else {
            return R.error("出差申请提交失败");
        }
    }

}
